﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WHC.Hotel.Entity;
using WHC.Hotel.BLL;
using WHC.OrderWater.Commons;


namespace WHC.Hotel.UI
{
    public partial class FrmEditRoomOrder : BaseForm
    {
        public RoomInfo RoomInfo = null;
        private Dictionary<string, RoomInfo> addedRooms = new Dictionary<string, RoomInfo>();
        private string billNumber = string.Empty;
        public FrmEditRoomOrder()
        {
            InitializeComponent();

            InitDictItems();
            InitUnitList();
          
        }

        private void InitDictItems()
        {
            this.txtPayType.Items.Clear();
            this.txtPayType.Items.AddRange(DictItemUtil.GetPayType());
            if (this.txtPayType.Items.Count > 0)
            {
                this.txtPayType.SelectedIndex = 0;
            }

            this.txtCustomerType.Items.Clear();
            this.txtCustomerType.Items.AddRange(DictItemUtil.GetCustomerType());
         
            if (this.txtCustomerType.Items.Count > 0)
            {
                this.txtCustomerType.SelectedIndex = 0;
            }

            this.txtCardType.Items.Clear();
            this.txtCardType.Items.AddRange(DictItemUtil.GetIDCarType());
            if (this.txtCardType.Items.Count > 0)
            {
                this.txtCardType.SelectedIndex = 0;
            }

            this.txtSource.Items.Clear();
            this.txtSource.Items.AddRange(DictItemUtil.GetCustomerSource());
            this.txtSource.Items.Insert(0, "未知");
            if (this.txtSource.Items.Count > 0)
            {
                this.txtSource.SelectedIndex = 0;
            }
        }

        private void FrmEditOrder_Load(object sender, EventArgs e)
        {
           // this.txtPrLivedDays.Focus();
            billNumber = Public.GetOrderNumber();
            txtOrderNo.Text = billNumber;
            txtPreOff.Text = Convert.ToDateTime(txtPreArrive.Text).AddDays(1).ToString("yyyy-MM-dd") + " 14:00";
            if (RoomInfo != null)
            {
                this.lblRoomNo.Text = RoomInfo.RoomNo;
                this.lblRoomType.Text = RoomInfo.RoomType;
                //this.lblAvailableNote.Text = string.Format("{0}可供房间", RoomInfo.RoomType);

                RoomTypeInfo typeInfo = BLLFactory<RoomType>.Instance.FindByName(RoomInfo.RoomType);
                if (typeInfo != null)
                {
                    this.lblOriginalPrice.Text = typeInfo.DayPrice.ToString("f2");
                    // this.txtDeposit.Text = typeInfo.DepositMoney.ToString("f2");
                    this.txtDicountPrice.Text = GetDiscountPrice().ToString("f2");

                    this.chkPartTime.Enabled = typeInfo.EnablePartTime;
                    this.txtPartTime.Tag = typeInfo;
                }

                addedRooms.Add(RoomInfo.RoomNo, RoomInfo);//默认增加一个
                InitAvailableRooms();
                RefreshAddedItems();
                RefreshPartTime();
            }
        
        }

        ///// <summary>
        ///// 根据用户的房间，获取可供的房间列表
        ///// </summary>
        //private void InitAvailableRooms()
        //{
        //    List<RoomInfo> roomList = BLLFactory<Room>.Instance.FindRoomsByCondition("   (Status='" + RoomStatus.空净房.ToString() + "' or Status='" + RoomStatus.空脏房.ToString() + "' ) ");
        //    this.lbxAvailable.Items.Clear();

        //    foreach (RoomInfo info in roomList)
        //    {
        //        if (!addedRooms.Contains(info.RoomNo))
        //        {
        //            this.lbxAvailable.Items.Add(info.RoomNo);
        //        }
        //    }
        //}

        /// <summary>
        /// 根据用户的房间，获取可供的房间列表
        /// </summary>
        private void InitAvailableRooms()
        {
            #region 项目类型信息明细类别

            this.treeView1.Nodes.Clear();
            this.treeView1.BeginUpdate();

            List<RoomTypeInfo> typeList = BLLFactory<RoomType>.Instance.GetAll();
            foreach (RoomTypeInfo typeInfo in typeList)
            {
                string nodeName = string.Format("{0}  {1}", typeInfo.Name, typeInfo.DayPrice.ToString("C2"));
                TreeNode typeNode = new TreeNode(nodeName, 0, 0);
                this.treeView1.Nodes.Add(typeNode);
                //typeNode.Tag = info;
                List<RoomInfo> roomList = BLLFactory<Room>.Instance.FindRoomsByCondition("   RoomType ='" + typeInfo.Name + "'  and    (Status='" + RoomStatus.空净房.ToString() + "' or Status='" + RoomStatus.空脏房.ToString() + "' ) ");

               // List<RoomInfo> roomList = BLLFactory<Room>.Instance.FindRooms(typeInfo.Name, RoomStatus.空净房.ToString());
                foreach (RoomInfo roomInfo in roomList)
                {
                    if (!addedRooms.ContainsKey(roomInfo.RoomNo))
                    {
                        TreeNode subNode = new TreeNode(roomInfo.RoomNo, 1, 1);
                        subNode.Tag = roomInfo;
                        typeNode.Nodes.Add(subNode);
                    }
                }
            }
            this.treeView1.EndUpdate();
            //this.treeView1.ExpandAll();

            #endregion
        }

        private decimal GetDiscountPrice()
        {
            return Convert.ToDecimal(this.txtDiscountRate.Text) *
                Convert.ToDecimal(this.lblOriginalPrice.Text);
        }

        private void chkPartTime_CheckedChanged(object sender, EventArgs e)
        {
            RefreshPartTime();
            RefreshAddedItems();
        }

        private void InitUnitList()
        {
            List<ProtocolUnitInfo> list = BLLFactory<ProtocolUnit>.Instance.GetAll();
            this.cmbUnit.Items.Clear();
            this.cmbUnit.Items.Add(new CListItem("请选择协议单位", "0"));
            foreach (ProtocolUnitInfo entity in list)
            {
                CListItem item = new CListItem(entity.UnitName, entity.Id.ToString());
                this.cmbUnit.Items.Add(item);
               
            }
            this.cmbUnit.SelectedIndex = 0;
           
        }
      
        private void RefreshPartTime()
        {
            RoomTypeInfo typeInfo = this.txtPartTime.Tag as RoomTypeInfo;
            if (typeInfo != null)
            {
                this.txtPartTime.Items.Clear();
                this.txtPartTime.Enabled = this.chkPartTime.Checked;
                this.txtPrLivedDays.Enabled = !this.chkPartTime.Checked;
                this.chkAutoRemember.Enabled = !this.chkPartTime.Checked;
                this.chkAutoRemember.Checked = !this.chkPartTime.Checked;

                if (this.chkPartTime.Checked)
                {
                    this.txtPartTime.Items.Add("标准:" + typeInfo.HourPrice.ToString());
                    this.txtPartTime.SelectedIndex = 0;
                    this.lblOriginalPrice.Text = typeInfo.HourPrice.ToString("f2");
                    this.txtDiscountRate.Text = "1.0";//钟点房不打折
                    this.txtDicountPrice.Text = GetDiscountPrice().ToString("f2");
                    this.txtPrLivedDays.Text = "0";
                }
                else
                {
                    this.lblOriginalPrice.Text = typeInfo.DayPrice.ToString("f2");

                    //非钟点房获取打折信息
                    string customerType = this.txtCustomerType.Text;
                    RoomDiscountInfo discountInfo = null;
                    if (customerType != "协议客户")
                    {
                    
                         discountInfo = BLLFactory<RoomType>.Instance.GetDiscountInfo(typeInfo.Name, customerType);

                    }
                    if (discountInfo != null)
                    {
                        this.txtDiscountRate.Text = discountInfo.DiscountRate.ToString("f2");
                        this.txtDicountPrice.Text = GetDiscountPrice().ToString("f2");
                    }

                   
                    this.txtPrLivedDays.Text = "1";                    
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeView1.SelectedNode;
            if (node != null && node.Tag != null)
            {
                RoomInfo info = node.Tag as RoomInfo;
                if (info != null)
                {
                    if (!addedRooms.ContainsKey(info.RoomNo))
                    {
                        addedRooms.Add(info.RoomNo, info);
                    }
                    InitAvailableRooms();
                    RefreshAddedItems();
                }
            }
        }


        private void RefreshAddedItems()
        {
            this.lsvAdded.Items.Clear();
            int i = 0;
            foreach (string roomNo in addedRooms.Keys)
            {
                ListViewItem lvItem = new ListViewItem((i + 1).ToString());
                lvItem.SubItems.Add(roomNo);

                RoomTypeInfo typeInfo = BLLFactory<RoomType>.Instance.FindByName(addedRooms[roomNo].RoomType);
                lvItem.SubItems.Add(typeInfo.Name);
                lvItem.SubItems.Add(typeInfo.DayPrice.ToString("f2"));

                decimal rate = 1.0M;
                RoomDiscountInfo discountInfo = null;

                if (chkPartTime.Checked)//钟点房
                {

                    lvItem.SubItems.Add(rate.ToString("f2"));
                    lvItem.SubItems.Add((typeInfo.HourPrice * rate).ToString("f2"));
                    lvItem.Tag = addedRooms[roomNo];

                }
                else
                {

                    if (this.txtCustomerType.Text != "协议客户")
                    {

                        if (cmbUnit.Text != "请选择协议单位")
                        {
                            DiscountInfoInfo mDiscountInfoInfo = BLLFactory<DiscountInfo>.Instance.FindSingle("  UnitName='" + cmbUnit.Text + "' and  RoomType ='" + typeInfo.Name + "'");
                            if (mDiscountInfoInfo != null)
                            {

                                rate = mDiscountInfoInfo.DiscountPercent;
                                lvItem.SubItems.Add(rate.ToString("f2"));
                                lvItem.SubItems.Add(mDiscountInfoInfo.RoomDiscountPrice.ToString("f2"));
                                lvItem.Tag = addedRooms[roomNo];
                            }

                        }
                        else
                        {

                            discountInfo = BLLFactory<RoomType>.Instance.GetDiscountInfo(typeInfo.Name, this.txtCustomerType.Text);
                            if (discountInfo != null)
                            {
                                rate = Convert.ToDecimal(discountInfo.DiscountRate);
                            }
                            lvItem.SubItems.Add(rate.ToString("f2"));
                            lvItem.SubItems.Add((typeInfo.DayPrice * rate).ToString("f2"));
                            lvItem.Tag = addedRooms[roomNo];

                        }


                    }
                    else//按协议单位处理
                    {

                        DiscountInfoInfo mDiscountInfoInfo = BLLFactory<DiscountInfo>.Instance.FindSingle("  UnitName='" + cmbUnit.Text + "' and  RoomType ='" + lblRoomType.Text + "'");
                        if (mDiscountInfoInfo != null)
                        {

                            rate = mDiscountInfoInfo.DiscountPercent;
                            lvItem.SubItems.Add(rate.ToString("f2"));
                            lvItem.SubItems.Add(mDiscountInfoInfo.RoomDiscountPrice.ToString("f2"));
                            lvItem.Tag = addedRooms[roomNo];
                        }


                    }

                }



                this.lsvAdded.Items.Add(lvItem);
                i++;
            }
        }



        private void btnRemove_Click(object sender, EventArgs e)
        {

            if (this.lsvAdded.SelectedItems.Count == 0)
                return;

            ListViewItem item = this.lsvAdded.SelectedItems[0];
            if (item != null && item.Tag != null)
            {
                RoomInfo info = item.Tag as RoomInfo;
                if (info != null && info.RoomNo != RoomInfo.RoomNo)
                {
                    addedRooms.Remove(info.RoomNo);
                }
            }

            InitAvailableRooms();
            RefreshAddedItems();
        }

        private void lbxAvailable_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            btnAdd_Click(null, null);
        }

        private void lsvAdded_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            btnRemove_Click(null, null);
        }

        private void ChangeCustomer(string customerID)
        {
            if (!string.IsNullOrEmpty(customerID))
            {
                CustomerInfo info = BLLFactory<Customer>.Instance.FindByID(customerID);
                if (info != null)
                {
                    this.txtAddress.Text = info.Address;
                    this.txtCardType.Text = info.IDCarType;
                    this.txtCompanyName.Text = info.CompanyName;

                    int i = txtCustomerType.FindStringExact(info.CustomerType);
                    this.txtCustomerType.SelectedIndex = i;
                    this.txtIDNumber.Text = info.IDNumber;
                    this.txtName.Text = info.Name;
                    this.txtSex.Text = info.Sex;
                    this.txtTelephone.Text = info.Telephone;
                    this.txtSource.Text = info.Source;
                    this.txtNote.Text = info.Note;
                }
            }
        }

        private void btnNameSearch_Click(object sender, EventArgs e)
        {
            FrmCustomerSearch dlg = new FrmCustomerSearch();
            dlg.txtName.Text = this.txtName.Text;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dlg.SelectedID))
                {
                    ChangeCustomer(dlg.SelectedID);
                }
            }
        }
        
        private void btnIDSearch_Click(object sender, EventArgs e)
        {
            FrmCustomerSearch dlg = new FrmCustomerSearch();
            dlg.txtName.Text = this.txtIDNumber.Text;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dlg.SelectedID))
                {
                    ChangeCustomer(dlg.SelectedID);
                }
            }
        }

        private void btnTelSearch_Click(object sender, EventArgs e)
        {
            FrmCustomerSearch dlg = new FrmCustomerSearch();
            dlg.txtName.Text = this.txtTelephone.Text;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(dlg.SelectedID))
                {
                    ChangeCustomer(dlg.SelectedID);
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            #region 输入检查

            this.DialogResult = DialogResult.None;
            if (this.txtName.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入主客姓名");
                this.txtName.Focus();
                return;
            }
            else if (this.txtIDNumber.Text.Trim().Length == 0)
            {
                MessageUtil.ShowTips("请输入证件编码");
                this.txtIDNumber.Focus();
                return;
            }
            else if (this.txtCustomerType.Text.Length == 0)
            {
                MessageUtil.ShowTips("请选择宾客类型");
                this.txtCustomerType.Focus();
                return;
            }
            if (txtCardType.Text == "身份证")
            {

                if (!Public.CheckIDCard(txtIDNumber.Text))
                {

                    MessageUtil.ShowTips("身份证号码不正确");
                    this.txtIDNumber.Focus();
                    return;
                
                }
            
            
            
            }

            if (txtCustomerType.Text == "协议客户" && cmbUnit.Text == "请选择协议单位")
            {


                MessageUtil.ShowTips("请选择协议单位");
                this.cmbUnit.Focus();
                return;
            
            }

            if (txtPayType.Text == "现金")
            {

                if (Convert.ToDecimal(txtDeposit.Text) < 1)
                {

                    MessageUtil.ShowTips("请输入实收押金金额");
                    this.txtDeposit.Focus();
                    return;

                }
            }
                
            string userName = this.txtName.Text.Trim();
            CustomerInfo existInfo = BLLFactory<Customer>.Instance.CheckUser(userName, this.txtIDNumber.Text);
            if (existInfo == null)
            {
                #region 确保数据库中存在指定的记录
                string message = string.Format("宾客信息在数据库中不存在，需要添加到数据库中才能下订单。\r\n您是否确定增加到数据库中？");
                if (MessageUtil.ShowYesNoAndTips(message) == DialogResult.No)
                {
                    return;
                }
                else
                {
                    try
                    {
                        bool success = AddCustomerToDB();
                        if (!success)
                        {
                            MessageUtil.ShowWarning("客户信息添加未成功");
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("客户信息添加出错", ex);
                        MessageUtil.ShowWarning("客户信息添加出错");
                        return;
                    }
                } 
                #endregion
            }

            #endregion

            #region 保存订单
            //万事俱备，只欠东风
            existInfo = BLLFactory<Customer>.Instance.CheckUser(userName, this.txtIDNumber.Text);
            if (existInfo != null)
            {
                try
                {
                    OrderInfo orderInfo = GetOrderMainInfo(existInfo);
                    for (int i = this.lsvAdded.Items.Count - 1; i >= 0; i--)
                    {
                       
                        //orderInfo.OriginalPrice = Convert.ToDecimal(this.lblOriginalPrice.Text);

                        //押金只属于主房间
                        if (lblRoomNo.Text == this.lsvAdded.Items[i].SubItems[1].Text)
                        {
                            orderInfo.DepositMoney = Convert.ToDecimal(this.txtDeposit.Text);
                           
                        }
                        else
                        {
                            //orderInfo.Persons =1;
                        }
                        orderInfo.DiscountPrice =Convert.ToDecimal(this.lsvAdded.Items[i].SubItems[5].Text);
                        orderInfo.DiscountRate =Convert.ToDouble(this.lsvAdded.Items[i].SubItems[4].Text);
                        orderInfo.RoomType = this.lsvAdded.Items[i].SubItems[2].Text;
                        orderInfo.OriginalPrice = Convert.ToDecimal(this.lsvAdded.Items[i].SubItems[3].Text);
                        orderInfo.RoomNo = this.lsvAdded.Items[i].SubItems[1].Text;//房间号
                        orderInfo.CheckType = 0;

                        int orderID = BLLFactory<Order>.Instance.Insert2(orderInfo);
                       // InitConsumer(orderID, orderInfo.RoomType, orderInfo.RoomNo);
                    }
                    MessageUtil.ShowTips("保存订单成功");
                    this.DialogResult = DialogResult.OK;
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError("保存订单出错：" + ex.Message);
                }
            } 
            #endregion
        }

        private void InitConsumer(int orderID, string roomType, string roomNo)
        {
            if (orderID > 0)
            {
                List<InitConsumerInfo> consumerList = BLLFactory<InitConsumer>.Instance.FindByRoomType(roomType);
                foreach (InitConsumerInfo initInfo in consumerList)
                {
                    ConsumerListInfo info = new ConsumerListInfo();
                    info.Amount = initInfo.Amount;
                    info.BeginTime = DateTime.Now;
                    info.Creator = Portal.gc.LoginInfo.FullName;
                    info.Discount = initInfo.Discount;
                    info.DiscountPrice = initInfo.DiscountPrice;
                    info.EndTime = DateTime.Now;
                    info.ItemNo = initInfo.ItemNo;
                    info.ItemName = initInfo.ItemName;
                    info.ItemType = initInfo.ItemType;
                    info.Order_ID = orderID;
                    info.Price = initInfo.Price;
                    info.Quantity = initInfo.Quantity;
                    info.RoomNo = roomNo;
                    info.Waiter = "*";

                    bool success = BLLFactory<ConsumerList>.Instance.Insert(info);
                    if (success)
                    {
                        BLLFactory<Goods>.Instance.AddStockQuantiy(info.ItemNo, info.ItemName, -Convert.ToInt32(info.Quantity));
                    }
                }
            }
        }

        /// <summary>
        /// 获取除房间和房间类型外的主订单信息
        /// </summary>
        /// <returns></returns>
        private OrderInfo GetOrderMainInfo(CustomerInfo existInfo)
        {
            OrderInfo orderInfo = new OrderInfo();
           
            orderInfo.CreateDate =Convert.ToDateTime(txtPreArrive.Text);
            orderInfo.Createor = Portal.gc.LoginInfo.FullName;
            orderInfo.Customer_ID = existInfo.ID;
            orderInfo.CustomerName = existInfo.Name;
            orderInfo.IDNumber = existInfo.IDNumber;
            orderInfo.Note = this.txtNote.Text;
            orderInfo.IsPartTime = this.chkPartTime.Checked;
            orderInfo.MasterRoomNo = this.lblRoomNo.Text;
            orderInfo.OrderNo = this.txtOrderNo.Text;
            orderInfo.BillNumber = billNumber;
            orderInfo.PayType = this.txtPayType.Text;
            orderInfo.Persons = Convert.ToInt32(this.txtPersons.Text);
            orderInfo.PreLivedDays = Convert.ToInt32(this.txtPrLivedDays.Text);
            orderInfo.IsCheckOut = false;
            orderInfo.IsEachPay = false;
            if (cmbUnit.Text == "请选择协议单位")
            {

                orderInfo.IsprotocolUnit = false;

            }
            else
            {

                orderInfo.IsprotocolUnit = true;
                orderInfo.ProtocolUnit = cmbUnit.Text;
                orderInfo.ProtocolUnitId = Convert.ToInt32(((CListItem)cmbUnit.SelectedItem).Value);
            
            }
            orderInfo.CreditCardMax = Convert.ToDecimal(txtCreditCardMax.Text);
            orderInfo.CreditCardNum = txtCreditCardNum.Text;
            orderInfo.PreGrantNum = txtPreGrantNum.Text;
            orderInfo.PreOffDate = Convert.ToDateTime(txtPreOff.Text);
            return orderInfo;
        }

        private bool AddCustomerToDB()
        {
            CustomerInfo info = new CustomerInfo();
            info.Name = this.txtName.Text.Trim();
            info.Address = this.txtAddress.Text;
            info.CompanyName = this.txtCompanyName.Text;
            info.CustomerType = this.txtCustomerType.Text;
            info.IDCarType = this.txtCardType.Text;
            info.IDNumber = this.txtIDNumber.Text;
            info.Note = this.txtNote.Text;
            info.RegistrationDate = DateTime.Now;
            info.Sex = this.txtSex.Text;
            info.Source = this.txtSource.Text;
            info.Telephone = this.txtTelephone.Text;
            

            return BLLFactory<Customer>.Instance.Insert(info);
        }

        private void txtCustomerType_SelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshPartTime();
        }

        private void cmbUnit_SelectedIndexChanged(object sender, EventArgs e)
        {


                    DiscountInfoInfo mDiscountInfoInfo = BLLFactory<DiscountInfo>.Instance.FindSingle("  UnitName='" + cmbUnit.Text + "' and  RoomType ='" + lblRoomType.Text+ "'");
                    if (mDiscountInfoInfo != null)
                    {

                        this.txtDicountPrice.Text = mDiscountInfoInfo.RoomDiscountPrice.ToString("f2");// mDiscountInfoInfo.DiscountPercent.ToString("f2");
                        this.txtDiscountRate.Text = (mDiscountInfoInfo.RoomDiscountPrice / Convert.ToDecimal(lblOriginalPrice.Text)).ToString("f2");
                    }
                    else
                    { 
                        this.txtDicountPrice.Text =lblOriginalPrice.Text;
                        this.txtDiscountRate.Text ="1";
                    
                    
                    }
                    RefreshAddedItems();


        }

      

        private void txtPrLivedDays_TextChanged(object sender, EventArgs e)
        {
           // txtPreOff.Text = Convert.ToDateTime(txtPreArrive.Text).AddDays(Convert.ToInt32(txtPrLivedDays.Text)).ToString("yyyy-MM-dd") + " 14:00";
        }

        private void txtPreArrive_ValueChanged(object sender, EventArgs e)
        {
            TimeSpan span = txtPreOff.Value.Subtract(txtPreArrive.Value.Date);
            txtPrLivedDays.Text = span.Days.ToString(); 

        }

        private void txtPreOff_ValueChanged(object sender, EventArgs e)
        {
            TimeSpan span = txtPreOff.Value.Subtract(txtPreArrive.Value.Date);
            txtPrLivedDays.Text = span.Days.ToString(); 
        }

       

      
      
    }
}
